<?php
/*
Plugin Name: url-slug-english
Plugin URI:  http://zengxiaoluan.com/url-slug-english
Description: 将Permalink(固定链接)里的中文翻译为英文
Version:     1.1
Author:      zengxiaoluan
Author URI:  http://zengxiaoluan.com/
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: url-slug-english
Domain Path: /languages
*/

/* Exit if accessed directly */
if ( ! defined( 'ABSPATH' ) ) exit;

$translation_from = get_option( 'translation_from', false );
$translation_from = !empty( $translation_from ) ? get_option( 'translation_from', false ) : 'baidu';

define('TRANSLATION_FROM', $translation_from);

include dirname( __FILE__ ) . '/includes/baidu_transapi.php';
include dirname( __FILE__ ) . '/includes/youdao_transapi.php';


function load_js(){
    wp_enqueue_script( 'apple-js', plugins_url( '/includes/scripts.js', __FILE__ ), array(), false, true );
}

add_action( 'admin_enqueue_scripts', 'load_js', 10, 1 );

/** Step 2 (from text above). */
add_action( 'admin_menu', 'apple_plugin_menu' );

/** Step 1. */
function apple_plugin_menu() {
    add_options_page( 'Apple Options', 'url-slug-english', 'manage_options', 'apple', 'apple_plugin_options' );
}

/** Step 3. */
function apple_plugin_options() {
    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }
    if ( isset( $_POST['apple_submit_hidden'] ) && $_POST['apple_submit_hidden'] == 'Y' ) {
        if ( (int) $_POST['translation_from'] == 1 ) {
            update_option( 'translation_from', 'baidu' );
            $baidu_app_id = isset( $_POST['baidu-app-id'] ) ? filter_var( $_POST['baidu-app-id'], FILTER_SANITIZE_STRING ) : null;
            $baidu_secret = isset( $_POST['baidu-secret'] ) ? filter_var( $_POST['baidu-secret'], FILTER_SANITIZE_STRING ) : null;
            $baidu_url    = isset( $_POST['baidu-url'] ) ? filter_var( $_POST['baidu-url'], FILTER_SANITIZE_STRING ) : null;
            if ( $baidu_app_id && $baidu_secret && $baidu_url ) {
                update_option( 'baidu-app-id', $baidu_app_id );
                update_option( 'baidu-secret', $baidu_secret );
                update_option( 'baidu-url', $baidu_url );
            }
        }
        if ( (int) $_POST['translation_from'] == 2 ) {
            update_option( 'translation_from', 'youdao' );
            $keyfrom = isset( $_POST['youdao-keyfrom'] ) ? filter_var( $_POST['youdao-keyfrom'], FILTER_SANITIZE_STRING ) : null;
            $api_key = isset( $_POST['youdao-api-key'] ) ? filter_var( $_POST['youdao-api-key'], FILTER_SANITIZE_STRING ) : null;
            if ( $keyfrom && $api_key ) {
                update_option( 'youdao-keyfrom', $keyfrom );
                update_option( 'youdao-api-key', $api_key );
            }
        }
      
    }
?>

    <div class="wrap">
        <h1>APPLE设置</h1>
        <form name="form1" id="baidu-apple" method="post" action="">
            <input type="hidden" name="apple_submit_hidden" value="Y" />
            <table class="form-table">
                <tr>
                    <th scope="row">设置你的翻译服务来源</th>
                    <td scope="row">
                        <select name="translation_from">
                            <option value="0">谷歌翻译</option>
                            <option value="1" <?php echo strcmp( TRANSLATION_FROM, 'baidu' ) == 0 ? 'selected="selected"' : '';?>">百度翻译</option>
                            <option value="2" <?php echo strcmp( TRANSLATION_FROM, 'youdao' ) == 0 ? 'selected="selected"' : '';?>">有道翻译</option>
                        </select>
                    </td>
                </tr>
            </table>
            <table class="form-table" id="baidu-translate">
                <tbody>
                    <tr>
                        <th scope="row"><label for="baidu-app-id">百度翻译APP ID</label></th>
                        <td>
                            <input type="text" name="baidu-app-id" id="baidu-app-id" class="regular-text ltr" value="<?php echo get_option( 'baidu-app-id' ); ?>" />
                            <p class="description">APP ID：20170213000038977</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="baidu-secret">百度翻译密钥</label></th>
                        <td>
                            <input type="text" name="baidu-secret" id="baidu-secret" class="regular-text ltr" value="<?php echo get_option( 'baidu-secret' ); ?>" />
                            <p class="description">密钥：rzQXw64mLFudDVzGADE_</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="baidu-url">翻译地址</label></th>
                        <td>
                            <input type="text" name="baidu-url" id="baidu-url" class="regular-text ltr" value="<?php echo get_option( 'baidu-url' ); ?>" />
                            <p class="description">翻译API HTTP地址：http://api.fanyi.baidu.com/api/trans/vip/translate</p>
                            <p class="description">翻译API HTTPS地址：https://fanyi-api.baidu.com/api/trans/vip/translate</p>
                        </td>
                    </tr>
                </tbody>
            </table>
            <table class="form-table" id="youdao-translate">
                <tbody>
                    <tr>
                        <th scope="row"><label for="baidu-app-id">keyfrom</label></th>
                        <td>
                            <input type="text" name="youdao-keyfrom" id="youdao-keyfrom" class="regular-text ltr" value="<?php echo get_option( 'youdao-keyfrom' ); ?>" />
                            <p class="description">zengxiaoluan</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="youdao-api-key">API key</label></th>
                        <td>
                            <input type="text" name="youdao-api-key" id="youdao-api-key" class="regular-text ltr" value="<?php echo get_option( 'youdao-api-key' ); ?>" />
                            <p class="description">399184121</p>
                        </td>
                    </tr>
                </tbody>
            </table>
            <p class="submit">
                <input type="submit" name="submit" class="button button-primary" value="<?php esc_attr_e( 'Save Changes' ) ?>" />
            </p>
        </form>
    </div>

<?php
}

/* 翻译函数 */
function new_post_name($post_ID, $title){
    if ( get_post_type( $post_ID ) == 'nav_menu_item' ) {
        return ;
    }

    if ( isset( $title ) && !empty( $title ) ) {
        $post_title = $title;
    }else{
        $post_title = get_the_title( $post_ID );
    }

    global $post_name;

    if ( TRANSLATION_FROM == 'baidu' ) {
        $res = baidu_translate( $post_title, 'zh', 'en' );

        if ( isset( $res['error_code'] ) ) {
            echo "<center><p>apple提示：翻译没有成功，请检查你的百度翻译配置。</p></center>";
            exit();
        }
        $post_name = $res['trans_result'][0]['dst'];
    }

    if ( TRANSLATION_FROM == 'youdao' ) {
        $post_name = youdao_translate( $post_title );
        if ( !$post_name ) {
            echo "<center><p>apple提示：翻译没有成功，请检查你的有道翻译配置。</p></center>";
            exit();
        }
    }

    // remove_action( 'save_post', __FUNCTION__ );

    return wp_update_post( array( 
        'ID' => $post_ID,
        'post_name' => $post_name
        ), false );

    // add_action( 'save_post', __FUNCTION__ );
}

/* 处理ajax请求 */
add_action( 'wp_ajax_nopriv_apple_action', 'apple_action');
add_action( 'wp_ajax_apple_action', 'apple_action');

function apple_action() {
    global $wpdb, $post_name; // this is how you get access to the database

    $title = $_POST['title'];
    $ID = $_POST['ID'];

    header( "Content-type: application/json" );

    if( is_numeric( new_post_name( $ID, $title ) ) ){
        echo json_encode( ['status' => true, 'post_name' => $post_name ] );
    }else{
        echo json_encode( ['status' => false] );
    }

    die();
}

/* 挂到action上 */
// add_action( 'save_post', 'new_post_name', 10, 3 );

if ( function_exists( 'apple_action' ) )
    /* 显示翻译按钮 */
    add_action( 'edit_form_before_permalink', function( $post ){
?>

<script type="text/javascript">
jQuery(document).ready(function($) {

    /* 用户编辑slug后再添加翻译按钮 */
    $('#edit-slug-buttons > .save').click(function(event) {
        setTimeout(function () {
            $('#edit-slug-box').append( '<span id="apple-translate" class="button button-small hide-if-no-js">翻译</span>' );
        }, 2000)
    });

    $('#edit-slug-box').append( '<span id="apple-translate" class="button button-small hide-if-no-js">翻译</span>' );
    $('#edit-slug-box').on('click', '#apple-translate', function(event) { 

        var data = {
            'action': 'apple_action',
            'title': $('#title').val(),
            'ID': parseInt( $('#post_ID').val() )
        }

        $.post(ajaxurl, data, function(response) {
            if ( response.status ) {
                var translated_post_name = response.post_name.toLowerCase().replace( ' ', '-' );
                $('#editable-post-name').html( translated_post_name )
                $('#new-post-slug').html( translated_post_name )
                $('#editable-post-name-full').html( translated_post_name )
                $('#post_name').val( translated_post_name )
                $('#edit-slug-box').append( '<span id="apple-message">翻译成功。</span>' );
            }else{
                $('#edit-slug-box').append( '<span id="apple-message">翻译失败。</span>' );
            }
            setTimeout(function () {
                $('#apple-message').fadeOut( '500' );
            }, 1500)
        });
        
    });
});
PHP = "<?php echo phpversion(); ?>";
</script>
<style>
    #apple-message{
        margin-left: 1em;
        color: #0073aa;
    }
</style>
<?php
    // var_dump( $post );
} );
?>